package com.googlecode.garbagecan.perf4jstudy;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;
import org.perf4j.LogParser;
import org.perf4j.helpers.GroupedTimingStatisticsTextFormatter;

public class LogParserUtil {
	public static void main(String[] args) throws Exception {
		parseLog("perf4j.log");
		System.out.println(parseLog2String("perf4j.log"));
	}
	
	public static void parseLog(String file) throws Exception {
		Reader reader = new InputStreamReader(new FileInputStream(new File(file).getAbsolutePath()));
		LogParser logParser = new LogParser(reader, System.out, null, 60 * 1000, true, new GroupedTimingStatisticsTextFormatter());
		logParser.parseLog();
		reader.close();
	}

	public static String parseLog2String(String file) throws Exception {
		Reader reader = new InputStreamReader(new FileInputStream(new File(file).getAbsolutePath()));
		StringOutputStream sos = new StringOutputStream();
		PrintStream ps = new PrintStream(sos);
		LogParser logParser = new LogParser(reader, ps, null, 60 * 1000, true, new GroupedTimingStatisticsTextFormatter());
		logParser.parseLog();
		String ret = sos.getBuffer();
		reader.close();
		ps.close();

		return ret;
	}
}

class StringOutputStream extends OutputStream {

	private StringBuffer sb;

	public StringOutputStream() {
		sb = new StringBuffer();
	}

	public void close() throws IOException{
		sb = null;
	}

	public void flush() throws IOException{

	}

	public void write(byte[] b) throws IOException{
		sb.append(new String(b));
	}

	public void write(byte[] b, int off, int len) throws IOException{
		sb.append(new String(b, off, len));
	}

	public void write(int b) throws IOException{
		sb.append(new String(new byte[]{(byte)b}));
	}

	public String getBuffer() throws IOException {
		return sb.toString();
	}
}
